#include "snake.h"
#include "game.h"

Snake::Snake() {
  int xt = head_x - t_size * (length - 1) * direction_x;
  int yt = head_y - t_size * (length - 1) * direction_y;

  for (int i = 0; i < length; i++) {
    deq.push_back(std::pair<int, int>(xt, yt));
    tmap[xt / 25][yt / 25] = 's';
    xt += direction_x * t_size;
    yt += direction_y * t_size;
  }

  std::cout << "Snake()\n";
  for (auto &pp : deq) {
    std::cout << pp.first << " " << pp.second << "\n";
  }
}

Snake::~Snake() {}

void Snake::init_draw() {
  glClear(GL_COLOR_BUFFER_BIT);

  glPointSize(t_size); // 设置点大小
  glBegin(GL_POINTS);
  glColor3f(1.0, 1.0, 1.0);
  for (auto &pp : deq) {
    glVertex2i(pp.first, pp.second);
  }
  glEnd();
  glFlush();
}

void Snake::auto_move() {
  tmap[deq.front().first / 25][deq.front().second / 25] = 0;
  head_x = head_x + t_size * direction_x;
  head_y = head_y + t_size * direction_y;

  // if (head_x < 0)  
  //   head_x = 787;  
  // if (head_y < 0)
  //   head_y = 787;
  // if (head_x > 800)
  //   head_x = 12;
  // if (head_y > 800)
  //   head_y = 12;
  if (head_x < 0 || head_y < 0 || head_x > 800 || head_y > 800 ||
      tmap[head_x / 25][head_y / 25] == 's') {
    game_over();
    return;
  }
  if (tmap[head_x / 25][head_y / 25] == 'f') {
    length++;
    score += (1200.0 / (double)speed_time);
    tmap[head_x / 25][head_y / 25] = 's';
    food();
    std::cout << "food\n";
    std::cout << score << "\n";
  } else {
    glPointSize(t_size); // 设置点大小
    glBegin(GL_POINTS);
    glColor3f(0.0, 0.0, 0.0);
    glVertex2i(deq.front().first, deq.front().second);
    glEnd();
    deq.pop_front();
  }

  tmap[head_x / 25][head_y / 25] = 's';
  deq.push_back(std::pair<int, int>(head_x, head_y));
  glBegin(GL_POINTS);
  glColor3f(1.0, 1.0, 1.0);
  glVertex2i(head_x, head_y);
  glEnd();
  glFlush();
  std::cout << head_x << " " << head_y << "\n";
}